import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {Observable, timer} from 'rxjs';
import {ElectronService} from 'ngx-electron';
import * as CryptoJS from 'crypto-js';


@Component({
  selector: 'app-lines',
  templateUrl: './lines.component.html',
  styleUrls: ['./lines.component.css']
})
export class LinesComponent implements OnInit {
  vmess;
  currentLine;
  delays = [];
  isSpinning = false;
  nzTip = '正在测试延迟';
  @Output() success = new EventEmitter();
  @Output() failed = new EventEmitter();
  constructor(private electron: ElectronService) { }

  ngOnInit() {
    const vmessfor = this.deepCopy(this.vmess);
    for (let i = 0; i < vmessfor.length; i ++) {
      this.vmess[i]['index'] = i;
      this.delays.push('');
    }
  }
  changeLine(line: any) {
    this.currentLine = line;
  }
  closeModal() {
    timer(100).subscribe(() => {
      this.success.emit(this.currentLine);
    });
  }
  tcpPing() {
    this.isSpinning = true;
    const vmessfor = this.deepCopy(this.vmess);
    for (let i = 0; i < vmessfor.length; i ++) {
      this.tcpService(this.vmess[i].vmess).subscribe((delay: string) => {
        this.delays[i] = delay;
        if (i === vmessfor.length - 1) {
          this.isSpinning = false;
        }
      });
    }
  }
  getPlatformInfo() {
    const currentPlatfrom = window.navigator.platform.toLocaleLowerCase();
    let platform;
    if (currentPlatfrom.indexOf('mac') !== -1) {
      platform = 'mac';
    } else if (currentPlatfrom.indexOf('win') !== -1) {
      platform = 'windows';
    } else if (currentPlatfrom.indexOf('linux') !== -1) {
      platform = 'linux';
    }
    return platform;
  }
  tcpService(vmess: string) {
    return new Observable((observable: any) => {
      if (this.electron.isElectronApp) {
        const ping = JSON.parse(CryptoJS.enc.Base64.parse(vmess.replace(/[\r\n]/g, '').replace('vmess://', '').trim().trim()).toString(CryptoJS.enc.Utf8));
        observable.next('--' + this.electron.ipcRenderer.sendSync('tcp-service-speed', {platform: this.getPlatformInfo(), pingInfo: JSON.stringify(ping)}));
      } else {
        try {
          observable.next(android.ping(vmess));
        } catch (e) {
          observable.next('');
        }
      }
    });
  }
  deepCopy(obj) {
    let newObj = obj;
    if (obj && typeof obj === 'object') {
      newObj = Object.prototype.toString.call(obj) === '[object Array]' ? [] : {};
      for (const i of Object.keys(obj)) {
        newObj[i] = this.deepCopy(obj[i]);
      }
    }
    return newObj;
  }
}
